////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                            //
//                                                         WNProject                                                          //
//                                                                                                                            //
//            This file is distributed under the BSD 2-Clause open source license. See License.txt for details.               //
//                                                                                                                            //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma once

#ifndef __WN_CONCURRENCY_SPIN_MUTEX_INL__
#define __WN_CONCURRENCY_SPIN_MUTEX_INL__

#include "WNCore/inc/WNAtomic.h"
#include "WNConcurrency/inc/WNThread.h"

namespace WNConcurrency {
    WN_FORCE_INLINE WNSpinMutex::WNSpinMutex() :
        mSpinFlag(0) {
    }

    WN_FORCE_INLINE WN_VOID WNSpinMutex::Lock() {
        while (WNAtomicCompareSwap(&mSpinFlag, 1, 0) != 0) {
            WNThreadYield();
        }
    }

    WN_FORCE_INLINE WN_BOOL WNSpinMutex::TryLock() {
        return(WNAtomicCompareSwap(&mSpinFlag, 1, 0) == 0 ? WN_TRUE : WN_FALSE);
    }

    WN_FORCE_INLINE WN_VOID WNSpinMutex::Unlock() {
        WNAtomicSwap(&mSpinFlag, 0);
    }
}

#endif // __WN_CONCURRENCY_SPIN_MUTEX_INL__